package com.cc.visitor.utils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @author chanchaw
 * @create 2025-02-12 9:03
 */
public class WordUtils {
    public static final String WORDFILE = "D:\\source\\java\\visitor\\doc\\visitword.docx";
    public static final String WORDFILE_NEW = "D:\\source\\java\\visitor\\doc\\visitword01.docx";
    public static final String IMG_FILE_FULL = "D:\\source\\java\\visitor\\doc\\11.png";
    public static final String IMG_FILE_NAME = "11.png";
    public static void main(String[] args) throws IOException, InvalidFormatException {
        // 加载Word模板
        FileInputStream fis = new FileInputStream(WORDFILE);
        XWPFDocument document = new XWPFDocument(fis);

        // 定义占位符和对应的值
        Map<String, String> placeholders = new HashMap<>();
        placeholders.put("${visitorName}", "chanchaw");
        placeholders.put("${visitorPhone}", "18001577776");
        placeholders.put("${visitorIdNumber}", "320304198412265551");
        placeholders.put("${visitorCompany}", "新东方智能化");
        placeholders.put("${intervieweeDepartment}", "品质保证部");
        placeholders.put("${intervieweeName}", "任月");
        placeholders.put("${sdate}", "2025-02-28");
        placeholders.put("${stime}", "13:00");
        placeholders.put("${edate}", "2025-02-28");
        placeholders.put("${etime}", "16:00");
        placeholders.put("${peopleNumber}", "2");
        placeholders.put("${plateNumber}", "");
        placeholders.put("${category}", "送货");
        placeholders.put("${remark}", "第一次生成word文件");

        // 替换占位符
        for (XWPFParagraph paragraph : document.getParagraphs()) {
            replacePlaceholders(paragraph, placeholders);
        }

        insertImage(document, IMG_FILE_FULL, IMG_FILE_NAME);

        // 保存修改后的文档
        FileOutputStream fos = new FileOutputStream(WORDFILE_NEW);
        document.write(fos);
        fos.close();
        document.close();
        fis.close();
    }

    /**
     * 将word模板文件导出为一个新的word文件，写入本地磁盘文件
     * @param wordFileTemplate 模板word文件，其中以 ${} 作为占位符
     * @param wordFileNew 生成的新的 word 文件的绝对路径+文件名
     * @param map 占位符对应的数据
     * @param imgFileFull 插入的图片绝对路径+文件名
     * @param imgFileName 插入的图片的纯文件名
     */
    public static void createWordFile(String wordFileTemplate, String wordFileNew,
                                  Map<String,String> map, String imgFileFull, String imgFileName) throws IOException, InvalidFormatException {// 根据模板创建word文档
        FileInputStream fis = new FileInputStream(wordFileTemplate);// 模板 word 文件
        XWPFDocument document = new XWPFDocument(fis);
        for (XWPFParagraph paragraph : document.getParagraphs()) {// 填充数据到占位符
            replacePlaceholders(paragraph, map);
        }
        insertImage(document, imgFileFull, imgFileName);// 添加图片
        FileOutputStream fos = new FileOutputStream(wordFileNew);// 生成新的文件 - 会覆盖原文件
        document.write(fos);
        fos.close();
        document.close();
        fis.close();
    }

    private static void replacePlaceholders(XWPFParagraph paragraph, Map<String, String> placeholders) {
        List<XWPFRun> runs = paragraph.getRuns();
        if (runs != null) {
            for (XWPFRun run : runs) {
                String text = run.getText(0);
                if (text != null) {
                    for (Map.Entry<String, String> entry : placeholders.entrySet()) {
                        if (text.contains(entry.getKey())) {
                            text = text.replace(entry.getKey(), entry.getValue());
                            run.setText(text, 0);
                        }
                    }
                }
            }
        }
    }
    private static void insertImage(XWPFDocument document, String imgFileFull, String imgFileName) throws IOException, InvalidFormatException {
        // 创建段落并插入图片
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
//        run.setText("Inserted Image:");

        // 插入图片
        FileInputStream imageStream = new FileInputStream(imgFileFull);
        run.addBreak();
        run.addPicture(imageStream, XWPFDocument.PICTURE_TYPE_JPEG, imgFileName, Units.toEMU(200), Units.toEMU(200));
        imageStream.close();
    }
}
